package com.neu.flashmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.easysdk.factory.Factory;
import com.github.pagehelper.PageInfo;
import com.neu.common.utils.Result;
import com.neu.flashmall.order.config.AliPayConfig;
import com.neu.flashmall.order.entity.OmsOrder;
import com.neu.flashmall.order.entity.OmsOrderItem;
import com.neu.flashmall.order.entity.OmsPayment;
import com.neu.flashmall.order.service.OmsOrderItemService;
import com.neu.flashmall.order.service.OmsOrderService;
import com.neu.flashmall.order.service.OmsPaymentService;
import com.neu.flashmall.order.vo.AliPay;
import com.neu.flashmall.order.vo.OmsOrderVo;
import com.neu.flashmall.order.vo.OrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oms_order")
@Api("订单Controller")
public class OmsOrderController {
    @Resource
    private OmsOrderService omsOrderService;
    @Resource
    private OmsOrderItemService omsOrderItemService;
    @Resource
    private OmsPaymentService omsPaymentService;

    @Resource
    private AlipayClient alipayClient = new AliPayConfig().alipayClient();

    public OmsOrderController() throws AlipayApiException {
    }

    @GetMapping(value = "/aliPay")
    @ApiOperation(value = "支付宝支付接口")
    public Result aliPay(Long orderId){
        AliPay aliPay = new AliPay();
        System.out.println(orderId);
        OmsOrderVo order = omsOrderService.getOrderById(orderId);
        System.out.println(order);
        aliPay.setOrderCode(order.getOrderCode());
        aliPay.setTotalAmount(order.getTotalAmount());
        List<OmsOrderItem> omsOrderItems = omsOrderItemService.selectAll(orderId);
        StringBuilder spuDesc = new StringBuilder();
        StringBuilder spuName = new StringBuilder();
        for(OmsOrderItem item:omsOrderItems){
            System.out.println(item.toString());
            spuDesc.append(item.getSkuName() + "X" + item.getSkuQuantity() + " ");
            spuName.append(item.getSpuName() + " ");
        }
        aliPay.setOrderDesc(spuDesc.toString());
        aliPay.setSpuName(spuName.toString());
        try{
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(AliPayConfig.NOTIFY_URL);
            request.setReturnUrl(AliPayConfig.RETURN_URL);

            request.setBizContent("{\"out_trade_no\":\""+ aliPay.getOrderCode() +"\","
                    + "\"total_amount\":\""+ aliPay.getTotalAmount().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() +"\","
                    + "\"subject\":\""+ aliPay.getSpuName() +"\","
                    + "\"body\":\""+ aliPay.getOrderDesc() +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                System.out.println("调用成功 ===>" + response.getBody());
                return Result.ok().put(response.getBody());
            } else {
                System.out.println("调用失败 ===>" + response.getCode() + "，返回描述 ===>" + response.getMsg());
                throw new RuntimeException("创建支付交易失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("创建支付交易失败");
        }
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String orderCode = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            OmsOrder order = omsOrderService.selectByOrderCode(orderCode);
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("****************验签通过****************");
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单为已支付
                omsOrderService.changeStatus(orderCode);
                System.out.println("更新订单状态");

                OmsPayment omsPayment = new OmsPayment();
                omsPayment.setOrderCode(orderCode);
                omsPayment.setOrderId(order.getId());
                omsPayment.setCreateTime(new SimpleDateFormat(("yyyy-MM-dd: hh24:mm:ss")).parse(gmtPayment));
                omsPayment.setPaymentStatus("已支付");
                omsPayment.setTotalAmount(order.getTotalAmount());
                omsPayment.setAlipayTradeNo(alipayTradeNo);
                omsPayment.setSubjectContent(params.get("subject"));

                //添加支付流水
                System.out.println("更新支付信息");
                omsPaymentService.insert(omsPayment);
            }
        }
        return "success";
    }

    @GetMapping("/getOrderById")
    @ApiOperation(value = "通过orderId查询订单信息")
    public Result getOrderById(@Param(value = "orderId") Long orderId){
        OmsOrderVo order = omsOrderService.getOrderById(orderId);
        return Result.ok().put(order);
    }

    @GetMapping("/getPaged")
    @ApiOperation("获取所有订单信息")
    public Result getPaged(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "3") Integer pageSize){
        //userUsername,orderCode,createTime,totalAmount,status,receiverName,receiverPhone,detailAddress(StringBuffer),(confirmStatus?deleteStatus?)
        PageInfo<OmsOrderVo> pageInfo = omsOrderService.selectAll(pageNum, pageSize);
        return Result.ok().put(pageInfo);
    }

    @GetMapping("/changeStatus")
    @ApiOperation("更改订单状态")
    public Result changeStatus(@Param("orderId") Long orderId){
        OmsOrder order = omsOrderService.selectByPrimaryKey(orderId);
        String result = omsOrderService.changeStatus(order.getOrderCode());
        if(result.equals("发货成功")){
            return Result.ok().setMessage(result);
        }else if(result.equals("付款成功")){
            return Result.ok().setMessage(result);
        }
        return Result.error().setMessage(result);
    }

    @GetMapping("/changeStatusByOrderCode")
    @ApiOperation("更改订单状态")
    public Result changeStatus(String orderCode){
        OmsOrder order = omsOrderService.selectByOrderCode(orderCode);
        order.setStatus(1);
        return Result.ok().put(omsOrderService.update(order));
    }

    @GetMapping("/changeConfirm")
    @ApiOperation("更改收货状态")
    public Result changeConfirm(@Param("orderId") Long orderId){
        String result = omsOrderService.changeConfirm(orderId);
        if(result.equals("收货成功")){
            return Result.ok().setMessage(result);
        }
        return Result.error().setMessage(result);
    }

    @GetMapping("/changeDelete")
    @ApiOperation("更改删除状态")
    public Result changeDelete(@Param("orderId") Long orderId){
        String result = omsOrderService.changeDelete(orderId);
        if(result.equals("修改删除状态失败")){
            return Result.error().setMessage(result);
        }
        return Result.ok().setMessage(result);
    }

    @GetMapping("/getOrderByStatus")
    @ApiOperation(value = "根据订单状态获取不同的订单")
    public Result getOrderByStatus(@Param(value = "pageNum") Integer pageNum,
                                   @Param(value = "pageSize") Integer pageSize,
                                   @Param(value = "statusName") String statusName){
        return Result.ok().put(omsOrderService.getOrderByStatus(pageNum,pageSize,statusName));
    }

    @PutMapping("/addOrder")
    public Result addOrder(@RequestBody OrderVo orderVo){
        String result = omsOrderService.addOrder(orderVo);
        if("添加订单成功".equals(result)){
            return Result.ok().setMessage(result).put(orderVo.getOrder().getId());
        }
        return Result.error().setMessage(result);
    }

    @GetMapping("/getOrderVo")
    public Result getOrderVo(Long id,Integer pageSize,Integer pageNum,Integer status){
        List<OrderVo> orderVoList = omsOrderService.getOrderVo(id,pageSize,pageNum,status);
        return Result.ok().put(orderVoList);
    }

    @GetMapping("/getOneOrder")
    public Result getOneOrder(Long id){
        OrderVo orderVo = omsOrderService.getOrderVo(id);
        return Result.ok().put(orderVo);
    }


    @GetMapping("/cancelOrder")
    public Result cancelOrder(Long id){
        int result = omsOrderService.changeStatus(id,4);
        if(result == 1){
            return Result.ok().setMessage("取消订单成功");
        }
        return Result.error();
    }

    @GetMapping("/completeOrder")
    public Result completeOrder(Long id){
        int result = omsOrderService.changeStatus(id,3);
        if(result == 1){
            return Result.ok().setMessage("订单已经确认完成");
        }
        return Result.error();
    }

    @GetMapping("/falseDelete")
    public Result deleteFalse(Long id){
        int result = omsOrderService.falseDelete(id);
        if(result == 1){
            return Result.ok().setMessage("删除订单成功");
        }
        return Result.error();
    }


}
